<template>
  <div class="content-box card">
    <div class="left-box">
      <div class="role-list">
        <div class="title">
          <span>角色列表</span>
          <el-button
            link
            type="primary"
            style="float: right; margin-top: 3px"
            @click="handleAddRole"
            plain
            v-auth="'role_index_save'"
          >
            <el-icon><Plus /></el-icon> 新增角色
          </el-button>
        </div>
        <el-radio-group v-model="roleId" @change="handleRoleChange">
          <el-radio class="role-item" :value="item.id" v-for="item in roleList" :key="item.id" size="large">
            {{ item.name }}
          </el-radio>
        </el-radio-group>
      </div>
    </div>
    <div class="right-box">
      <div class="title">{{ title }}</div>
      <div style="margin-top: 30px">
        <el-form>
          <el-form-item label="角色名称">
            <el-input ref="roleNameRef" v-model="roleName" style="width: 515px; margin-left: 10px" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色权限">
            <el-tree
              :data="permissionList"
              show-checkbox
              node-key="id"
              default-expand-all
              :props="{ class: customNodeClass }"
              ref="treeRef"
            >
              <template #default="{ data }">
                <div>
                  <span>{{ data.title }}</span>
                </div>
              </template>
            </el-tree>
          </el-form-item>
          <el-form-item style="margin-left: 80px">
            <el-button type="primary" @click="handleSaveRole" style="width: 120px" plain v-auth="'role_index_save'">
              <el-icon><Plus /></el-icon> 保存
            </el-button>
            <el-button type="danger" @click="handleDeleteRole" style="width: 120px" plain v-auth="'role_index_remove'">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="role_index">
import type { TreeInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { getRoleList, getPermissionTree, getRolePermissions, deleteRole, saveRole } from "@/api/modules/role";
import { Role } from "@/api/interface/index";
import { ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";

const treeRef = ref<TreeInstance>();
const roleNameRef = ref<any>();
const roleId = ref(0);
const roleName = ref("");
const roleNameOld = ref("");
const roleList = ref<Role.ResRoleList[]>([]);
const permissionList = ref<Role.PermissionNode[]>([]);
const title = ref("角色详情");

onMounted(async () => {
  // 加载角色列表
  const reqRoleParams: Role.ReqRoleParams = {};
  const res = await getRoleList(reqRoleParams);
  roleList.value = res.data || [];
  if (roleList.value.length > 0) {
    // 默认选择第一个角色
    roleId.value = roleList.value[0].id;
    handleRoleChange(roleId.value);
  }

  // 加载公司所有权限
  const res1 = await getPermissionTree();
  permissionList.value = res1.data || [];
});

// 角色选择改变时，加载角色权限
const handleRoleChange = async (val: any) => {
  title.value = "角色详情";
  roleName.value = roleList.value.find(item => item.id === val)?.name || "";
  roleNameRef.value.focus();

  // 获取角色权限
  const res = await getRolePermissions(val);
  treeRef.value!.setCheckedKeys(res.data, true);
  roleNameOld.value = roleName.value;
};

// 自定义节点类名
const customNodeClass = (data: any) => {
  if (data.type === "功能权限") {
    return "tree-fun-node";
  }
  if (data.type === "页面权限") {
    return "tree-page-node";
  }
  return "";
};

// 新增角色
const handleAddRole = () => {
  roleId.value = 0;
  roleName.value = "";
  title.value = "新增角色";
  roleNameRef.value.focus();
};

// 保存角色
const handleSaveRole = async () => {
  if (roleName.value === "") {
    ElMessage("请输入角色名称");
    return;
  }
  const allSelectPermissionIds = treeRef.value!.getCheckedNodes(false, true).map(item => item.id);
  const selectAllPermissionIds = treeRef.value!.getCheckedKeys().map(item => Number(item));
  const halfSelectedPermissionIds: number[] = allSelectPermissionIds.filter(element => !selectAllPermissionIds.includes(element));

  const reqParams: Role.ReqRoleSaveParams = {
    id: roleId.value,
    name: roleName.value,
    selectAllPermissionIds: selectAllPermissionIds,
    halfSelectedPermissionIds: halfSelectedPermissionIds
  };
  const savRes = await saveRole(reqParams);
  roleId.value = savRes.data;
  ElMessage({
    message: "保存成功",
    type: "success"
  });

  // 刷新角色列表
  const reqRoleParams: Role.ReqRoleParams = {};
  const res = await getRoleList(reqRoleParams);
  roleList.value = res.data || [];
};

// 删除角色
const handleDeleteRole = () => {
  if (roleId.value === 0) {
    ElMessage("请选择角色");
    return;
  }
  ElMessageBox.confirm("确定删除角色[ " + roleNameOld.value + " ] ？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const params: Role.ReqRoleDeleteParams = { ids: [roleId.value] };
    await deleteRole(params);
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    // 刷新角色列表
    const reqRoleParams: Role.ReqRoleParams = {};
    const res = await getRoleList(reqRoleParams);
    roleList.value = res.data || [];
    if (roleList.value.length > 0) {
      roleId.value = roleList.value[0].id;
      handleRoleChange(roleId.value);
    }
  });
};
</script>
<style scoped lang="scss">
@import "./index";
</style>
<style>
.tree-page-node .el-tree-node__children {
  padding-left: 58px;
}
.tree-fun-node {
  display: inline-block;
  float: left;
  width: auto;
}
.tree-fun-node .el-tree-node__content {
  padding-right: 6px !important;
  padding-left: 6px !important;
  margin-right: 2px;
  margin-left: 2px;
}
.tree-fun-node .el-tree-node__content > .el-tree-node__expand-icon {
  display: none;
}
</style>
